<template>
  <div class="medical-homepage">
    <!-- 顶部搜索栏 -->
    <div class="header">
      <!-- 返回按钮 -->
      <div class="back-button">
        <el-button
            @click="goBack"
            :icon="ArrowLeft"
            text
            class="back-btn"
        >
          返回
        </el-button>
      </div>
      <div class="search-box">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索机构"
            class="search-input"
            @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 分隔线 -->
    <div class="divider"></div>

    <!-- 功能导航 -->
    <div class="nav-section">
      <div class="nav-item" @click="handleNavClick('register')">
        <div class="nav-icon">
          <el-icon><Calendar /></el-icon>
        </div>
        <div class="nav-text">挂号</div>
      </div>
    </div>

    <!-- 分隔线 -->
    <div class="divider"></div>

    <!-- 附近机构 -->
    <div class="nearby-section">
      <div class="section-title">附近机构</div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="4" animated />
      </div>

      <!-- 机构列表 -->
      <div v-else class="hospital-list">
        <div
            v-for="institution in institutionList"
            :key="institution.hospitalId"
            class="hospital-card"
            @click="handleInstitutionClick(institution.hospitalId)"
        >
          <div class="hospital-badge" :class="getLevelClass(institution.grade)">
            {{ getLevelText(institution.grade) }}
          </div>
          <div class="hospital-info">
            <div class="hospital-name">{{ institution.hospitalName }}</div>
            <div class="hospital-level">机构等级：{{ getLevelText(institution.grade) || '暂无等级信息' }}</div>
            <div class="hospital-address">
              <span class="address">{{ getFullAddress(institution) || '地址未知' }}</span>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="institutionList.length === 0" class="empty-state">
          <el-empty description="暂无机构数据" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  Search,
  Calendar,
  ArrowLeft
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { listHospital } from '@/api/institution/hospital.js'

const router = useRouter()
const searchKeyword = ref('')
const loading = ref(false)
const institutionList = ref([])

// 返回函数
const goBack = () => {
  router.push('/userIndex')
}

// 页面加载时获取机构数据
onMounted(() => {
  loadInstitutionData()
})

// 加载机构数据
const loadInstitutionData = async () => {
  try {
    loading.value = true
    const response = await listHospital({
      pageNum: 1,
      pageSize: 10,
    })
    console.log('机构数据响应:', response)
    institutionList.value = response.rows || response.data || []
    console.log('处理后的机构列表:', institutionList.value)
  } catch (error) {
    console.error('加载机构数据失败:', error)
    ElMessage.error('加载机构数据失败')
    institutionList.value = []
  } finally {
    loading.value = false
  }
}

// 获取完整地址
const getFullAddress = (institution) => {
  if (!institution) return ''

  const { province, city, district, address } = institution
  const addressParts = []

  if (province) addressParts.push(province)
  if (city) addressParts.push(city)
  if (district) addressParts.push(district)
  if (address) addressParts.push(address)

  return addressParts.length > 0 ? addressParts.join('') : ''
}

// 获取机构等级对应的CSS类
const getLevelClass = (grade) => {
  if (!grade) return 'level-other'

  const gradeStr = grade.toString().toLowerCase()
  const levelMap = {
    '3a': 'level-3a',
    '三级甲等': 'level-3a',
    '三甲': 'level-3a',
    '2a': 'level-2a',
    '二级甲等': 'level-2a',
    '二甲': 'level-2a',
    '1a': 'level-1a',
    '一级甲等': 'level-1a',
    '一甲': 'level-1a',
  }
  return levelMap[gradeStr] || 'level-other'
}

// 获取机构等级显示文本
const getLevelText = (grade) => {
  if (!grade) return '医疗机构'

  const gradeStr = grade.toString()
  const levelTextMap = {
    '3a': '三甲',
    '三级甲等': '三甲',
    '2a': '二甲',
    '二级甲等': '二甲',
    '1a': '一甲',
    '一级甲等': '一甲',
  }

  if (['三甲', '二甲', '一甲', '三级甲等', '二级甲等', '一级甲等'].includes(gradeStr)) {
    return gradeStr
  }

  return levelTextMap[gradeStr] || gradeStr || '医疗机构'
}

// 搜索处理
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    ElMessage.info(`搜索关键词: ${searchKeyword.value}`)
    filterInstitutions(searchKeyword.value)
  } else {
    loadInstitutionData()
  }
}

// 根据关键词过滤机构
const filterInstitutions = async (keyword) => {
  try {
    loading.value = true
    const response = await listHospital({
      pageNum: 1,
      pageSize: 10,
      hospitalName: keyword
    })
    institutionList.value = response.rows || response.data || []
  } catch (error) {
    console.error('搜索机构失败:', error)
    ElMessage.error('搜索失败')
    institutionList.value = []
  } finally {
    loading.value = false
  }
}

// 导航点击处理 - 跳转到挂号页面
const handleNavClick = (type) => {
  if (type === 'register') {
    router.push('/medical/registration')
  }
}

// 机构点击处理
const handleInstitutionClick = (institutionId) => {
  ElMessage.info(`查看机构详情: ${institutionId}`)
  // 可以跳转到机构详情页面
}
</script>

<style scoped lang="scss">
.medical-homepage {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 20px;
}

// 顶部搜索栏
.header {
  display: flex;
  align-items: center;
  padding: 16px;
  background: white;
  gap: 12px;

  // 返回按钮样式
  .back-button {
    .back-btn {
      padding: 8px 12px;
      color: #409eff;
      font-size: 14px;
      border: none;

      &:hover {
        background-color: #f0f7ff;
        color: #79bbff;
      }
    }
  }

  .search-box {
    flex: 1;

    .search-input {
      :deep(.el-input__inner) {
        border-radius: 20px;
        background: #f5f5f5;
        border: none;
        height: 36px;
      }

      :deep(.el-input__prefix) {
        display: flex;
        align-items: center;
        margin-left: 8px;
      }
    }
  }
}

// 分隔线
.divider {
  height: 8px;
  background: #f0f2f5;
}

// 功能导航
.nav-section {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
  background: white;

  .nav-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    cursor: pointer;

    .nav-icon {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      background: linear-gradient(135deg, #409eff, #79bbff);
      display: flex;
      align-items: center;
      justify-content: center;

      .el-icon {
        font-size: 24px;
        color: white;
      }
    }

    .nav-text {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }

    &:hover {
      opacity: 0.8;
      transform: translateY(-2px);
      transition: all 0.3s ease;
    }
  }
}

// 附近机构区域
.nearby-section {
  background: white;
  padding: 16px;

  .section-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 16px;
    padding-left: 8px;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background: #409eff;
      border-radius: 2px;
    }
  }

  .hospital-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
}

// 加载状态
.loading-container {
  padding: 20px 0;
}

// 空状态
.empty-state {
  padding: 40px 0;
}

// 机构卡片
.hospital-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }

  .hospital-badge {
    position: absolute;
    top: 16px;
    right: 16px;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;

    &.level-3a {
      background: #fef0f0;
      color: #f56c6c;
      border: 1px solid #fbc4c4;
    }

    &.level-2a {
      background: #f0f9ff;
      color: #409eff;
      border: 1px solid #b3d8ff;
    }

    &.level-1a {
      background: #f0f9f0;
      color: #67c23a;
      border: 1px solid #c2e7b0;
    }

    &.level-other {
      background: #f5f5f5;
      color: #909399;
      border: 1px solid #dcdfe6;
    }
  }

  .hospital-info {
    .hospital-name {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 8px;
      line-height: 1.4;
    }

    .hospital-level {
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
      line-height: 1.4;
    }

    .hospital-address {
      display: flex;
      align-items: center;
      font-size: 13px;

      .address {
        color: #999;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .header {
    padding: 12px;

    .back-button {
      .back-btn {
        padding: 6px 10px;
        font-size: 12px;
      }
    }
  }

  .nav-section {
    padding: 16px 0;

    .nav-item {
      .nav-icon {
        width: 40px;
        height: 40px;

        .el-icon {
          font-size: 20px;
        }
      }

      .nav-text {
        font-size: 12px;
      }
    }
  }

  .nearby-section {
    padding: 12px;

    .section-title {
      font-size: 16px;
    }
  }

  .hospital-card {
    padding: 12px;

    .hospital-info {
      .hospital-name {
        font-size: 15px;
      }

      .hospital-level {
        font-size: 13px;
      }

      .hospital-address {
        font-size: 12px;
      }
    }
  }
}

// 动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.hospital-card {
  animation: fadeIn 0.5s ease-out;
}
</style>